﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TestProject.LiveTissWCF;
using System.IO;
using System.Security.Cryptography;

namespace TestProject
{
    public class TestUtils
    {
        #region Auth
        /// <summary>
        /// Chave AES
        /// </summary>
        private static byte[] Key { get; set; }
        /// <summary>
        /// Valores Iniciais do AES
        /// </summary>
        private static byte[] IV { get; set; }
        /// <summary>
        /// Converte uma string de valores hexadecimal para array de byte correspondente
        /// </summary>
        /// <param name="HexString">String de valores hexadecimal</param>
        /// <returns>Array de bytes correspondente a string</returns>
        private static byte[] ToByteArray(string HexString)
        {
            int NumberChars = HexString.Length;
            byte[] bytes = new byte[NumberChars / 2];
            for (int i = 0; i < NumberChars; i += 2)
            {
                bytes[i / 2] = Convert.ToByte(HexString.Substring(i, 2), 16);
            }
            return bytes;
        }
        /// <summary>
        /// Converte um array de bytes em uma string de valores hexadecimal
        /// </summary>
        /// <param name="bytes">Array de bytes</param>
        /// <returns>string de valores hexadecimal</returns>
        private static string ToString(byte[] bytes)
        {
            StringBuilder sb = new StringBuilder(bytes.Length * 2);
            foreach (byte b in bytes)
            {
                sb.AppendFormat("{0:x2}", b);
            }
            return sb.ToString();
        }
        /// <summary>
        /// Criptografa a string s usando AES
        /// </summary>
        /// <param name="s">String para criptografar</param>
        /// <returns>String criptografada</returns>
        private static string Encrypt(string plainText)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the streams used
            // to encrypt to an in memory
            // array of bytes.
            MemoryStream msEncrypt = null;
            CryptoStream csEncrypt = null;
            StreamWriter swEncrypt = null;

            // Declare the RijndaelManaged object
            // used to encrypt the data.
            AesManaged aesAlg = null;

            try
            {
                // Create a RijndaelManaged object
                // with the specified key and IV.
                aesAlg = new AesManaged();
                aesAlg.Key = Key;
                aesAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = aesAlg.CreateEncryptor();

                // Create the streams used for encryption.
                msEncrypt = new MemoryStream();
                csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
                swEncrypt = new StreamWriter(csEncrypt);

                //Write all data to the stream.
                swEncrypt.Write(plainText);

            }
            finally
            {
                // Clean things up.

                // Close the streams.
                if (swEncrypt != null)
                    swEncrypt.Close();
                if (csEncrypt != null)
                    csEncrypt.Close();
                if (msEncrypt != null)
                    msEncrypt.Close();

                // Clear the RijndaelManaged object.
                if (aesAlg != null)
                    aesAlg.Clear();
            }

            // Return the encrypted bytes from the memory stream.
            return ToString(msEncrypt.ToArray());

        }
        /// <summary>
        /// Construtor estatico
        /// </summary>
        static TestUtils()
        {
            Key = ToByteArray("7624fd0c34c42da20512c0df0a321230");
            IV = ToByteArray("00000000000000000000000000000000");
        }
        #endregion

        public static AuthenticationToken Token { get; set; }

        public static AuthenticationToken GenerateToken(string login, string password)
        {
            AuthenticationToken userToken = new AuthenticationToken();

            userToken.Login = Encrypt(login);
            userToken.Password = Encrypt(password);

            return userToken;
        }
    }
}
